package com.corpgovernment.organization.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.applytrip.apply.request.ApplyTripRequest;
import com.corpgovernment.api.applytrip.soa.request.ApplyTripPersonEffectRequest;
import com.corpgovernment.api.applytrip.soa.response.TripPersonEffectResponse;
import com.corpgovernment.api.applytrip.vo.AoApplyTripTempVo;
import com.corpgovernment.api.costcenter.model.CostCenter;
import com.corpgovernment.api.organization.bo.GetPassengerResponseBO;
import com.corpgovernment.api.organization.model.bookingrelation.BookingRange;
import com.corpgovernment.api.organization.model.passenger.*;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerByUidResponse;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerNameRequest;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerNameResponse;
import com.corpgovernment.api.organization.soa.switchbo.getPassengerByUidRequest;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.dto.CheckRepeatDto;
import com.corpgovernment.common.enums.SiteEnum;
import com.corpgovernment.common.utils.Pinyin4jUtil;
import com.corpgovernment.costcenter.service.impl.CostCenterServiceImpl;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.dataloader.ApplyTripClientLoader;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.CardCodeEnum;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.corpgovernment.organization.enumm.DefaultBookRangeEnum;
import com.corpgovernment.organization.enumm.ProductTypeEnum;
import com.corpgovernment.organization.factory.PassengerServiceFactory;
import com.corpgovernment.organization.model.DeletePassengerRequest;
import com.corpgovernment.organization.model.SavePassengerRequest;
import com.corpgovernment.organization.model.SavePassengerResponse;
import com.corpgovernment.organization.service.*;
import com.corpgovernment.organization.service.impl.FreshPassengerRelationServiceImpl;
import com.corpgovernment.organization.util.CardTypeSwitchUtil;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.vo.GetPassengerRequestVO;
import com.corpgovernment.organization.vo.GetPassengerResponseVO;
import com.ctrip.corp.obt.generic.security.context.SecurityContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 出行人列表
 *
 * @author wangyujue
 */
@RestController
@RequestMapping("/passenger")
@Slf4j
public class PassengerController {

    private static final String ADD = "add";
    private static final String NO_EMPLOYEE = "非员工";
    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private IOrgUserIdCardService organizationUserIdCardService;
    @Autowired
    private IOrganizationNonEmployeeService organizationNonEmployeeService;
	@Autowired
	private IFreshPassengerService freshPassengerService;
	@Autowired
	private ApplyTripClientLoader applyTripClientLoader;
	@Autowired
	private BookingRelationService bookingRelationService;
	@Autowired
	private CostCenterServiceImpl costCenterService;
	@Autowired
	private FreshPassengerRelationServiceImpl freshPassengerRelationService;
	@Autowired
	private OrganizationApollo organizationApollo;
	@Autowired
	private PassengerService passengerService;
	@Autowired
	private PassengerServiceFactory passengerServiceFactory;

	/**
     * 检查出行人列表
     * 1.维护新鲜度
     * 2.用户证件信息维护
     * 3.用户信息维护
     * 4.非员工新增
     * 5.维护人员的常旅关系
     *
     * @return
     */
    @RequestMapping("/checkPassenger")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<Boolean> checkPassenger(@RequestBody CheckPassengerRequest checkPassengerRequest) {
        log.info("检查出行人列表接口开始[{}]", JsonUtils.toJsonString(checkPassengerRequest));
        List<PassengerVo> passengerVos = checkPassengerRequest.getPassengerVos();
        if (CollectionUtils.isEmpty(passengerVos)) {
            return JSONResult.errorMsg("passengerVos不能为空");
        }
        String uid = checkPassengerRequest.getUid();

        // 筛选出员工
        List<PassengerVo> employeeList = passengerVos.stream().filter(PassengerVo::getCorp).collect(Collectors.toList());
        // 筛选出非员工
        List<PassengerVo> nonEmployeeList = passengerVos.stream().filter(p -> !p.getCorp()).collect(Collectors.toList());

        // #1.员工操作
        List<String> uids = employeeList.stream().filter(p -> p != null).filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerVo::getUid).collect(Collectors.toList());
        List<MbOrgUserIdcard> needAddList = new ArrayList<>();
        List<MbOrgUserIdcard> needUpdateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(uids)) {
            // 查询员工证件列表
            List<MbOrgUserIdcard> mbOrgUserIdcardList = organizationUserIdCardService.batchFindByUids(uids);
            Map<String, List<MbOrgUserIdcard>> cardListMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(mbOrgUserIdcardList)) {
                cardListMap = mbOrgUserIdcardList.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
            }
            // 组装数据, 组装出需要修改的证件数据和新增的证件数据
            packageData(employeeList, cardListMap, needAddList, needUpdateList, true);
        }


        // #2.非员工操作
        List<PassengerVo> needSaveNonEmployeeList = nonEmployeeList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).filter(p -> startsWith(p.getNoEmployeeId(), ADD, false)).collect(Collectors.toList());
        List<PassengerVo> nonEmplooyeeCheckList = nonEmployeeList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).filter(p -> !startsWith(p.getNoEmployeeId(), ADD, false)).collect(Collectors.toList());
        List<Long> nonEmployeeUids = nonEmplooyeeCheckList.stream().map(p -> Long.parseLong(p.getNoEmployeeId())).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(nonEmployeeUids)) {
            List<MbOrgUserIdcard> nonEmployeeCardList = organizationUserIdCardService.batchFindByNonEmployeeUids(nonEmployeeUids);
            Map<String, List<MbOrgUserIdcard>> nonEmployeeCardListMap = nonEmployeeCardList.stream().collect(Collectors.groupingBy(p -> p.getNonEmployeeId().toString()));
            // 组装数据(已经有的出行人，判断数据是否修改)
            packageData(nonEmplooyeeCheckList, nonEmployeeCardListMap, needAddList, needUpdateList, false);
        }

        // #3. DB操作
        // 保存新建的非员工
        List<MbFreshPassenger> needSaveFreshPassengerList = new ArrayList<>();
        for (PassengerVo passengerVo : needSaveNonEmployeeList) {
            MbOrgNonEmployeeInfo mbOrgNonEmployeeInfo = new MbOrgNonEmployeeInfo();
            mbOrgNonEmployeeInfo.setEmployeeUid(uid);
            mbOrgNonEmployeeInfo.setName(passengerVo.getName());
            mbOrgNonEmployeeInfo.setNationality(passengerVo.getNationality());
            mbOrgNonEmployeeInfo.setGender(passengerVo.getGender());
            mbOrgNonEmployeeInfo.setEmployeeType(passengerVo.getEmployeeType());
            mbOrgNonEmployeeInfo.setEmail(passengerVo.getMail());
            MobilePhoneVo tel = passengerVo.getTel();
            if (tel != null) {
                String countryCode = tel.getCountryCode();
                String value = tel.getValue();
                if (StringUtils.isNotBlank(countryCode) && StringUtils.isNotBlank(value)) {
                    String mobilePhone = countryCode + " " + value;
                    mbOrgNonEmployeeInfo.setMobilePhone(mobilePhone);
                }
            }
            String passport = passengerVo.getPassport();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(passport)) {
                String[] split = passport.split("/");
                if (split.length == 1) {
                    mbOrgNonEmployeeInfo.setFirstEnName(split[0]);
                } else if (split.length == 2) {
                    mbOrgNonEmployeeInfo.setFirstEnName(split[0]);
                    mbOrgNonEmployeeInfo.setLastEnName(split[1]);
                }
            }
            // 生日
            PassengerVo.Birth birth = passengerVo.getBirth();
            if (birth != null) {
                String birthValue = birth.getValue();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(birthValue)) {
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date parse = sf.parse(birthValue);
                        mbOrgNonEmployeeInfo.setBirthday(parse);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            NameInfoBo nameInfoBo = new NameInfoBo();
            nameInfoBo.setSurname(passengerVo.getSurname());
            nameInfoBo.setGivenname(passengerVo.getGivenname());
            nameInfoBo.setFullName(StrUtil.isNotBlank(passengerVo.getFullName())?passengerVo.getFullName():passengerVo.getName());
            nameInfoBo.setNationality(passengerVo.getNationality());
            if(StrUtils.checkNameInfo(nameInfoBo)){
                mbOrgNonEmployeeInfo.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
            }
            organizationNonEmployeeService.save(mbOrgNonEmployeeInfo);
            List<CardVo> source = passengerVo.getSource();
            for (CardVo cardVo : source) {
                MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
                mbOrgUserIdcard.setNonEmployeeId(mbOrgNonEmployeeInfo.getId());
                mbOrgUserIdcard.setCardType(cardVo.getType());
                mbOrgUserIdcard.setCardNo(cardVo.getValue());
                mbOrgUserIdcard.setPlaceOfIssue(cardVo.getPlaceOfIssue());
                mbOrgUserIdcard.setTimeLimit(cardVo.getValidity());
                needAddList.add(mbOrgUserIdcard);
            }
            // 需要插入出行人新鲜度表
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setNonEmployeeUid(mbOrgNonEmployeeInfo.getId());
            mbFreshPassenger.setCreateUid(uid);
            mbFreshPassenger.setName(passengerVo.getName());
            mbFreshPassenger.setEnName(passengerVo.getPassport());
			mbFreshPassenger.setValid(false);
            passengerVo.setNoEmployeeId(String.valueOf(mbOrgNonEmployeeInfo.getId()));
            needSaveFreshPassengerList.add(mbFreshPassenger);
        }
        // 保存新建证件
        if (CollectionUtils.isNotEmpty(needAddList)) {
            organizationUserIdCardService.batchSave(needAddList);
        }
        // 修改证件
        log.info("需要修改的证件信息为:{}", JsonUtils.toJsonString(needUpdateList));
        for (MbOrgUserIdcard mbOrgUserIdcard : needUpdateList) {
            if (mbOrgUserIdcard.getNonEmployeeId() != null) {
                organizationUserIdCardService.updateNonEmployeeCard(mbOrgUserIdcard);
            } else {
                organizationUserIdCardService.update(mbOrgUserIdcard);
            }
        }

        // 维护员工信息
        if (CollectionUtils.isNotEmpty(employeeList)) {
            for (PassengerVo passengerVo : employeeList) {
                MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
                mbOrgEmployeeInfo.setUid(passengerVo.getUid());
                MobilePhoneVo tel = passengerVo.getTel();
                if (tel != null) {
                    String countryCode = tel.getCountryCode();
                    String value = tel.getValue();
                    mbOrgEmployeeInfo.setAreaCode(countryCode);
                    mbOrgEmployeeInfo.setMobilePhone(value);
                }
                mbOrgEmployeeInfo.setNationality(passengerVo.getNationality());
                mbOrgEmployeeInfo.setEmail(passengerVo.getMail());
                String gender = passengerVo.getGender();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(gender)) {
                    mbOrgEmployeeInfo.setGender(gender);
                }
                String passport = passengerVo.getPassport();
                if (StringUtils.isNotBlank(passport)) {
                    String[] split = passport.split("/");
                    if (split != null && split.length > 0) {
                        mbOrgEmployeeInfo.setFirstEnName(split[0]);
                        if (split.length == 2) {
                            mbOrgEmployeeInfo.setLastEnName(split[1]);
                        }
                    }
                }
                PassengerVo.Birth birth = passengerVo.getBirth();
                if (birth != null) {
                    String birthValue = birth.getValue();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(birthValue)) {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            Date parse = sf.parse(birthValue);
                            mbOrgEmployeeInfo.setBirthday(parse);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                NameInfoBo nameInfoBo = new NameInfoBo();
                nameInfoBo.setSurname(passengerVo.getSurname());
                nameInfoBo.setGivenname(passengerVo.getGivenname());
                nameInfoBo.setFullName(StrUtil.isNotBlank(passengerVo.getFullName())?passengerVo.getFullName():passengerVo.getName());
                nameInfoBo.setNationality(passengerVo.getNationality());

                if(StrUtils.checkNameInfo(nameInfoBo)){
                    mbOrgEmployeeInfo.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
                }
                // 维护员工表
                organizationEmployeeService.update(mbOrgEmployeeInfo);
                // 维护fresh表
                MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
                mbFreshPassenger.setEmployeeUid(passengerVo.getUid());
                mbFreshPassenger.setName(passengerVo.getName());
                mbFreshPassenger.setEnName(passengerVo.getPassport());
                boolean b = freshPassengerService.updateByEmployeeId(mbFreshPassenger);
            }
        }
        // 维护非员工信息
        if (CollectionUtils.isNotEmpty(nonEmplooyeeCheckList)) {
            for (PassengerVo passengerVo : nonEmplooyeeCheckList) {
                MbOrgNonEmployeeInfo mbOrgNonEmployeeInfo = new MbOrgNonEmployeeInfo();
                mbOrgNonEmployeeInfo.setId(Long.valueOf(passengerVo.getNoEmployeeId()));
                MobilePhoneVo tel = passengerVo.getTel();
                if (tel != null) {
                    String countryCode = tel.getCountryCode();
                    String value = tel.getValue();
                    if (StringUtils.isNotBlank(countryCode) && StringUtils.isNotBlank(value)) {
                        String mobilePhone = countryCode + " " + value;
                        mbOrgNonEmployeeInfo.setMobilePhone(mobilePhone);
                    }
                }
                mbOrgNonEmployeeInfo.setNationality(passengerVo.getNationality());
                mbOrgNonEmployeeInfo.setEmail(passengerVo.getMail());
                String gender = passengerVo.getGender();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(gender)) {
                    mbOrgNonEmployeeInfo.setGender(gender);
                }
                String passport = passengerVo.getPassport();
                if (StringUtils.isNotBlank(passport)) {
                    String[] split = passport.split("/");
                    if(split.length == 2){
                        mbOrgNonEmployeeInfo.setFirstEnName(split[0]);
                        mbOrgNonEmployeeInfo.setLastEnName(split[1]);
                    }
                }
                PassengerVo.Birth birth = passengerVo.getBirth();
                if (birth != null) {
                    String birthValue = birth.getValue();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(birthValue)) {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            Date parse = sf.parse(birthValue);
                            mbOrgNonEmployeeInfo.setBirthday(parse);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                mbOrgNonEmployeeInfo.setName(passengerVo.getName());
                mbOrgNonEmployeeInfo.setEmployeeType(passengerVo.getEmployeeType());
                // 维护非员工表
                NameInfoBo nameInfoBo = new NameInfoBo();
                nameInfoBo.setSurname(passengerVo.getSurname());
                nameInfoBo.setGivenname(passengerVo.getGivenname());
                nameInfoBo.setFullName(StrUtil.isNotBlank(passengerVo.getFullName())?passengerVo.getFullName():passengerVo.getName());
                nameInfoBo.setNationality(passengerVo.getNationality());
                if(StrUtils.checkNameInfo(nameInfoBo)){
                    mbOrgNonEmployeeInfo.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
                }
                organizationNonEmployeeService.update(mbOrgNonEmployeeInfo);
                // 维护fresh表
                MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
                mbFreshPassenger.setNonEmployeeUid(Long.valueOf(passengerVo.getNoEmployeeId()));
                mbFreshPassenger.setName(passengerVo.getName());
                mbFreshPassenger.setEnName(passengerVo.getPassport());
                boolean b = freshPassengerService.updateByNonEmployeeId(mbFreshPassenger);
            }
        }

        // #4.维护新鲜度
        List<MbFreshPassenger> freshList = new ArrayList<>();
        for (PassengerVo passengerVo : employeeList) {
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setEmployeeUid(passengerVo.getUid());
            freshList.add(mbFreshPassenger);
        }
        for (PassengerVo passengerVo : nonEmployeeList) {
            if (StringUtils.isNotBlank(passengerVo.getNoEmployeeId()) && !startsWith(passengerVo.getNoEmployeeId(), ADD, false)) {
                MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
                mbFreshPassenger.setNonEmployeeUid(Long.parseLong(passengerVo.getNoEmployeeId()));
                freshList.add(mbFreshPassenger);
            }
        }
        if (CollectionUtils.isNotEmpty(freshList)) {
            freshPassengerService.fresh(freshList);
        }
        if (CollectionUtils.isNotEmpty(needSaveFreshPassengerList)) {
            freshPassengerService.batchSave(needSaveFreshPassengerList);
        }
        //#5 维护人员的常旅关系
        Map<Long, MbFreshPassenger> needSaveFreshPassengerMap = null;
        MbFreshPassenger needNoFreshPassenger = null;
        //处理新增的非员工，设置id
        if (CollectionUtils.isEmpty(needSaveFreshPassengerList)) {
            needSaveFreshPassengerMap = needSaveFreshPassengerList.stream().collect(Collectors.toMap(x -> x.getNonEmployeeUid(), x -> x, (k1, k2) -> k1));
            for (PassengerVo passengerVo : needSaveNonEmployeeList) {
                needNoFreshPassenger = needSaveFreshPassengerMap.get(Long.valueOf(passengerVo.getNoEmployeeId()));
                passengerVo.setId(needNoFreshPassenger.getId());
            }
        }
        //处理所有需要维护的数据
        List<PassengerVo> relation = new ArrayList<>();
        relation.addAll(nonEmplooyeeCheckList);
        relation.addAll(employeeList);
        relation.addAll(needSaveNonEmployeeList);
        MbFreshPassengerRelation freshPassengerRelation = null;
        MbFreshPassengerRelation exited = null;
        List<MbFreshPassengerRelation> addList = new ArrayList<>();
        List<Long> freshTimeList = new ArrayList<>();
        List<Long> deletedList = new ArrayList<>();
        //查询已存在的所以常旅
        List<MbFreshPassengerRelation> exitedList = freshPassengerRelationService.selectByUid(checkPassengerRequest.getUid());
        Map<String, MbFreshPassengerRelation> exitedMap = null;
        if (!CollectionUtils.isEmpty(exitedList)) {
            exitedMap = exitedList.stream().collect(Collectors.toMap(MbFreshPassengerRelation::getFreshUid, x -> x, (k1, k2) -> k1));
        }
        log.info("exitedMap:{}", JsonUtils.toJsonString(exitedMap));
        Date date = null;
        log.info("操作新鲜度表数据:{}", JsonUtils.toJsonString(relation));
        for (PassengerVo passengerVo : relation) {
            //更新为不关联
            if (passengerVo.getRelationId() != null && (passengerVo.getRelationFlag() == null || !passengerVo.getRelationFlag())) {
                deletedList.add(passengerVo.getRelationId());
            }
            //刷新
            if (passengerVo.getRelationId() != null && (passengerVo.getRelationFlag() != null && passengerVo.getRelationFlag())) {
                freshTimeList.add(passengerVo.getRelationId());
            }
            //新增
            if (passengerVo.getRelationId() == null && (passengerVo.getRelationFlag() != null && passengerVo.getRelationFlag())) {
                freshPassengerRelation = new MbFreshPassengerRelation();
                date = new Date();
                freshPassengerRelation.setDatachangeCreatetime(date);
                freshPassengerRelation.setDatachangeLasttime(date);
                freshPassengerRelation.setIsDeleted(false);
                freshPassengerRelation.setUid(checkPassengerRequest.getUid());
                freshPassengerRelation.setFreshTime(date);
                freshPassengerRelation.setEmployeeFlag(StringUtils.isEmpty(passengerVo.getUid()) ? 0 : 1);
                freshPassengerRelation.setFreshUid(StringUtils.isEmpty(passengerVo.getUid()) ? passengerVo.getNoEmployeeId() : passengerVo.getUid());
                //新增
                if (exitedMap != null) {
                    exited = exitedMap.get(StringUtils.isEmpty(passengerVo.getUid()) ? passengerVo.getNoEmployeeId() : passengerVo.getUid());
                }
                if (exited == null) {
                    addList.add(freshPassengerRelation);
                } else {
                    //更新刷新时间
                    freshTimeList.add(exited.getId());
                }
            }
        }
        log.info("操作新鲜度表动作数据 添加:{}，删除:{}, 修改:{}",
                JsonUtils.toJsonString(addList), JsonUtils.toJsonString(deletedList), JsonUtils.toJsonString(freshTimeList));
        //新增
        if (!CollectionUtils.isEmpty(addList)) {
            log.info("addList:{}", JsonUtils.toJsonString(addList));
            freshPassengerRelationService.save(addList);
        }
        //更新时间
        if (!CollectionUtils.isEmpty(freshTimeList)) {
            freshPassengerRelationService.updateFreshTime(freshTimeList);
        }
        //解除关系
        if (!CollectionUtils.isEmpty(deletedList)) {
            freshPassengerRelationService.deletedRelation(deletedList);
        }
        return JSONResult.success(true);
    }

    private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
        if (str != null && prefix != null) {
            return prefix.length() > str.length() ? false : str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
        } else {
            return str == null && prefix == null;
        }
    }


    private void packageData(List<PassengerVo> list,
                             Map<String, List<MbOrgUserIdcard>> map,
                             List<MbOrgUserIdcard> needAddList,
                             List<MbOrgUserIdcard> needUpdateList,
                             boolean ifCorp) {
        for (PassengerVo passengerVo : list) {
            List<CardVo> source = passengerVo.getSource();
            List<MbOrgUserIdcard> userIdcards = null;
            if (ifCorp) {
                userIdcards = map.get(passengerVo.getUid());
            } else {
                userIdcards = map.get(passengerVo.getNoEmployeeId());
            }
            Map<Integer, MbOrgUserIdcard> userCardMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(userIdcards)) {
                userCardMap = userIdcards.stream().distinct().collect(Collectors.toMap(MbOrgUserIdcard::getCardType, mbOrgUserIdcard -> mbOrgUserIdcard));
            }
            if (CollUtil.isNotEmpty(source)) {
                for (CardVo cardVo : source) {
                    MbOrgUserIdcard mbOrgUserIdcard = null;
                    if (MapUtils.isNotEmpty(userCardMap)) {
                        mbOrgUserIdcard = userCardMap.get(cardVo.getType());
                    }
                    // 需要新增
                    if (mbOrgUserIdcard == null) {
                        MbOrgUserIdcard needAdd = new MbOrgUserIdcard();
                        if (ifCorp) {
                            needAdd.setEmployeeUid(passengerVo.getUid());
                        } else {
                            needAdd.setNonEmployeeId(Long.valueOf(passengerVo.getNoEmployeeId()));
                        }
                        needAdd.setCardNo(cardVo.getValue());
                        needAdd.setCardType(cardVo.getType());
                        needAdd.setTimeLimit(cardVo.getValidity());
                        needAdd.setPlaceOfIssue(cardVo.getPlaceOfIssue());
                        needAddList.add(needAdd);
                        continue;
                    }
                    String value = cardVo.getValue();
                    // 需要修改
                    boolean updateFlag = !mbOrgUserIdcard.getCardNo().equals(value)
                            || (mbOrgUserIdcard.getCardType() == 2 && mbOrgUserIdcard.getTimeLimit() != cardVo.getValidity());
                    if (updateFlag) {
                        MbOrgUserIdcard needUpdate = new MbOrgUserIdcard();
                        if (ifCorp) {
                            needUpdate.setEmployeeUid(passengerVo.getUid());
                        } else {
                            needUpdate.setNonEmployeeId(Long.valueOf(passengerVo.getNoEmployeeId()));
                        }
                        needUpdate.setId(mbOrgUserIdcard.getId());
                        needUpdate.setCardNo(cardVo.getValue());
                        needUpdate.setCardType(cardVo.getType());
                        needUpdate.setTimeLimit(cardVo.getValidity());
                        needUpdate.setPlaceOfIssue(cardVo.getPlaceOfIssue());
                        needUpdateList.add(needUpdate);
                    }
                }
            }
        }
    }

    /**
     * 出行人列表
     * localhost:7890/passenger/getPassenger
     *
     * @param request
     * @return
     */
    @RequestMapping("/getPassenger")
    public JSONResult<Map<String, Object>> getPassenger(@RequestBody GetPassengerRequest request, BaseUserInfo baseUserInfo) {
        request.setOrgId(baseUserInfo.getOrgId());
        if (!"admin".equals(baseUserInfo.getUid())){
            request.setUid(baseUserInfo.getUid());
        }
        return getPassengerSoa(request);
    }

    /**
     * 出行人列表
     * localhost:7890/passenger/getPassenger
     *
     * @param request
     * @return
     */
    @RequestMapping("/getPassengerSoa")
    public JSONResult<Map<String, Object>> getPassengerSoa(@RequestBody GetPassengerRequest request) {
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("showAdd", false);
        returnMap.put("plist", new ArrayList<>());

        // 出行类型，PUB因公、OWN因私
        String corpPayType = request.getCorpPayType();
        // 0 - 出行人 ， 1- 代理审批人
        Integer type = request.getType();
        // 业务类型
        String site = request.getSite();
        // 前端选中用户列表
		List<PassengerInfo> selectedList = request.getSelectedList();
        // 用户名匹配查询条件
        String query = request.getQuery();
        // 用户id
        String currentUid = request.getUid();
        // 出差申请单号
        String travelId = request.getTravelId();
        Integer page = request.getPage();
        String orgId = request.getOrgId();
        // 走出差申请查人的逻辑
		boolean isPub = CorpPayTypeEnum.PUB.toString().equals(corpPayType);

		if (isPub && StringUtils.isNotBlank(travelId) && applyTripClientLoader.needVerifyPerson(travelId)) {
			List<PassengerVo> returnList = getPassengerByTravel(request);
			Map<String, CostCenter> costMap = Maps.newHashMap();
			for (PassengerVo passengerVo : returnList) {
				CostCenter costCenter = costMap.get(passengerVo.getOrgId());
				if (costCenter == null) {
					List<CostCenter> costCenters = costCenterService.getCostCenter(passengerVo.getOrgId());
					if (CollectionUtils.isNotEmpty(costCenters)){
                        costMap.putIfAbsent(passengerVo.getOrgId(), costCenters.get(0));
                        passengerVo.setCostCenter(costCenter);
                    }
				} else {
					passengerVo.setCostCenter(costCenter);
				}
			}
			returnMap.put("plist", returnList);
			return new JSONResult<>(returnMap);
		}

        List<String> selectedUids = new ArrayList<>();
        List<Long> selectedNoEmpIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(selectedList)) {
			selectedUids = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerInfo::getUid).collect(Collectors.toList());
			selectedNoEmpIds = selectedList.stream().filter(p -> p.getNoEmployeeId() != null).filter(p -> !startsWith(p.getNoEmployeeId(), "add", false)).map(p -> Long.valueOf(p.getNoEmployeeId())).collect(Collectors.toList());
        }

        List<PassengerVo> returnList = new ArrayList<>();
		List<MbFreshPassenger> mbFreshPassengers = new ArrayList<>();
		MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(request.getUid());
		if (mbOrgEmployeeInfo == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
		}
		// 能代订的组织结构范围
		List<String> bookRangeOrgIds = new ArrayList<>();
		// 是否可以代订非员工
		Boolean bookForNonEmp = Boolean.FALSE;
		List<String> orgRange = null;
		String bookRangeCode = organizationApollo.getDefaultBookRange();
		log.info("默认的代订范围：{}", bookRangeCode);
		DefaultBookRangeEnum bookRangeEnum = DefaultBookRangeEnum.getByCode(bookRangeCode);
		if (isPub && bookRangeEnum == DefaultBookRangeEnum.All) {
			List<MbOrgInfo> allOrgList = organizationInfoService.listAll();
			List<String> orgIds = allOrgList.stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList());
			orgRange = orgIds;
			currentUid = null;
			CollUtil.addAll(bookRangeOrgIds, orgIds);
		} else if (StrUtil.equals(site, SiteEnum.FLIGHTINTL.getCode())) {
			// 国籍机票产线出行人逻辑：企业管理-新建国际机票需求单，可搜索和添加的乘机人范围自动为全公司所有人。不受配置的代订范围影响。
			bookForNonEmp = Boolean.TRUE;
			CollUtil.addAll(bookRangeOrgIds, organizationInfoService.listRecentCompanyDirectDepartmentWithCompanyByOrgId(orgId));
		} else {
			BookingRange bookingRange = bookingRelationService.queryBookingRangeByUidAndOrgId(currentUid, orgId);
			log.info("代定范围：{}", JsonUtils.toJsonString(bookingRange));
			if (bookingRange != null) {
				bookForNonEmp = bookingRange.getBookForNonEmp();
				// 过滤掉状态为禁用的组织结构
				orgRange = bookingRange.getBookingRange();
				if (CollUtil.isNotEmpty(orgRange)) {
					List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByOrgIds(orgRange);
                    if (CollUtil.isNotEmpty(mbOrgInfoList)) {
                        bookRangeOrgIds.addAll(mbOrgInfoList.stream().filter(p -> p.getValid().equals(CommonConst.TRUE)).map(MbOrgInfo::getOrgId).collect(Collectors.toList()));
                    }
                }
            }
        }
        // 过滤掉重复数据
        bookRangeOrgIds = CollUtil.distinct(bookRangeOrgIds);
        log.info("可定范围：{}", JsonUtils.toJsonString(bookRangeOrgIds));
        // 出行人逻辑
        if (type != null && type == 0) {
            // #1.如果是因公，查询用户的代订范围，再加上用户所在的组织。能不能预订非员工根据设置判断
            if (corpPayType.equals(CorpPayTypeEnum.PUB.toString())) {
                // 查询非员工
                if (bookForNonEmp) {
                    if (StringUtils.isBlank(query)) {
                        mbFreshPassengers = freshPassengerService.listByOrgIdsAndUid(
                                bookRangeOrgIds, currentUid, selectedUids, selectedNoEmpIds,
                                request.getOrgId(), request.getPage(), CommonConst.PAGE_SIZE_30);
                    } else if (StringUtils.isNotBlank(query)) {
                        mbFreshPassengers = freshPassengerService.listByOrgIdsAndUidAndName(
                                bookRangeOrgIds, currentUid, query, selectedUids, selectedNoEmpIds,
                                request.getOrgId(), request.getPage(), CommonConst.PAGE_SIZE_30);
                    }
                    returnMap.put("showAdd", true);
                } else {
                    // 不查询非员工
                    if (StringUtils.isBlank(query)) {
                        mbFreshPassengers = freshPassengerService.listByOrgIds(
                                bookRangeOrgIds, currentUid, selectedUids, selectedNoEmpIds,
                                request.getOrgId(), request.getPage(), CommonConst.PAGE_SIZE_30);
                    } else if (StringUtils.isNotBlank(query)) {
                        mbFreshPassengers = freshPassengerService.listByOrgIdsAndName(
                                bookRangeOrgIds, currentUid, query, selectedUids, selectedNoEmpIds,
                                request.getOrgId(), request.getPage(), CommonConst.PAGE_SIZE_30);
                    }
                }
                if (!StrUtil.equals(site, SiteEnum.FLIGHTINTL.getCode()) && CollectionUtils.isEmpty(orgRange)) {
                    //保留自己
                    if (!CollectionUtils.isEmpty(mbFreshPassengers)) {
						String finalCurrentUid = currentUid;
						mbFreshPassengers = mbFreshPassengers.stream().filter(x -> (StringUtils.isEmpty(x.getEmployeeUid()) || x.getEmployeeUid().equals(finalCurrentUid))).collect(Collectors.toList());
                    }
                }
            } else {
				// #2.因私默认是自己加非员工
				log.info("因私查询出行人currentUid：{}，orgId：{}，selectedNoEmpIds：{}，selectedUids：{}，query：{}", currentUid, orgId, selectedNoEmpIds, selectedUids, query);
				mbFreshPassengers = freshPassengerService.listNonEmployeeByUid(currentUid, orgId, selectedNoEmpIds, selectedUids, query, CommonConst.PAGE_SIZE_30, page);
				log.info("因私查询到的出行人：{}", JsonUtils.toJsonString(mbFreshPassengers));
				returnMap.put("showAdd", true);
			}
        } else if (type != null && type == 1) {
            // 代理审批人逻辑
            // 查询本部门的
            if (StringUtils.isBlank(query)) {
                mbFreshPassengers = freshPassengerService.listByOrgId(orgId, currentUid, request.getPage(), selectedUids, selectedNoEmpIds, CommonConst.PAGE_SIZE_30);
            } else if (StringUtils.isNotBlank(query)) {
                mbFreshPassengers = freshPassengerService.listByOrgIdAndName(orgId, currentUid, query, request.getPage(), selectedUids, selectedNoEmpIds, CommonConst.PAGE_SIZE_30);
            }
        }
        if (CollectionUtils.isEmpty(mbFreshPassengers)) {
            return new JSONResult<>(returnMap);
        }

        List<String> employeeUidList = mbFreshPassengers.stream().filter(p -> StringUtils.isNotBlank(p.getEmployeeUid())).distinct().map(MbFreshPassenger::getEmployeeUid).collect(Collectors.toList());
        Map<String, List<MbOrgUserIdcard>> uidCardMapList = new HashMap<>(16);
        Map<String, MbOrgEmployeeInfo> employeeInfoMap = new HashMap<>(16);
        if (CollectionUtils.isNotEmpty(employeeUidList)) {
            // #1.员工证件信息
            List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(employeeUidList);
            uidCardMapList = userIdcards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
            // #2.员工信息
            List<MbOrgEmployeeInfo> mbOrgEmployeeInfos = organizationEmployeeService.listByUids(employeeUidList);
            employeeInfoMap = mbOrgEmployeeInfos.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
        }

        List<Long> nonEmployeeUidList = mbFreshPassengers.stream().filter(p -> p.getNonEmployeeUid() != null).map(MbFreshPassenger::getNonEmployeeUid).collect(Collectors.toList());
        Map<Long, List<MbOrgUserIdcard>> nonUidCardMapList = new HashMap<>(16);
		Map<Long, MbOrgNonEmployeeInfo> nonEmployeeInfoMap = new HashMap<>(16);
		if (CollectionUtils.isNotEmpty(nonEmployeeUidList)) {
			// #1.非员工证件信息
			List<MbOrgUserIdcard> nonEmpIdCards = organizationUserIdCardService.batchFindByNonEmployeeUids(nonEmployeeUidList);
			nonUidCardMapList = nonEmpIdCards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getNonEmployeeId));
			// #2.非员工信息
			List<MbOrgNonEmployeeInfo> mbOrgNonEmployeeInfos = organizationNonEmployeeService.listByIds(nonEmployeeUidList);
			nonEmployeeInfoMap = mbOrgNonEmployeeInfos.stream().collect(Collectors.toMap(MbOrgNonEmployeeInfo::getId, p -> p));
		}

		// 组织架构信息
		List<String> beQueryOrgIds = mbFreshPassengers.stream().map(MbFreshPassenger::getOrgId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
		Map<String, MbOrgInfo> orgInfoMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(beQueryOrgIds)) {
			List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(beQueryOrgIds);
			orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
		}

		PageInfo<MbFreshPassenger> pageInfo = new PageInfo<>(mbFreshPassengers);
		int totalPage = pageInfo.getPages();
		boolean pageEnd = false;
		if (request.getPage() == totalPage) {
			pageEnd = true;
		}
		Map<String, CostCenter> costMap = new HashMap<>();
		for (MbFreshPassenger mbFreshPassenger : mbFreshPassengers) {
			PassengerVo passengerVo = new PassengerVo();
			passengerVo.setId(mbFreshPassenger.getId());
			List<MbOrgUserIdcard> cards = null;
			if (StringUtils.isNotBlank(mbFreshPassenger.getEmployeeUid())) {
				cards = uidCardMapList.get(mbFreshPassenger.getEmployeeUid());
				MbOrgEmployeeInfo userInfo = employeeInfoMap.get(mbFreshPassenger.getEmployeeUid());
				if (userInfo == null) {
					continue;
				}
				passengerVo.setUid(userInfo.getUid());
				String eName = "";
				if (StringUtils.isNotBlank(userInfo.getFirstEnName())
						|| StringUtils.isNotBlank(userInfo.getMidEnName()) || StringUtils.isNotBlank(userInfo.getLastEnName())) {
					eName = (StringUtils.isNotBlank(userInfo.getFirstEnName()) ? userInfo.getFirstEnName() : "")
                            + (StringUtils.isNotBlank(userInfo.getMidEnName()) ? userInfo.getMidEnName() : "")
                            + "/" + (StringUtils.isNotBlank(userInfo.getLastEnName()) ? userInfo.getLastEnName() : "");
                }
                passengerVo.setPassport(eName);
                MbOrgInfo mbOrgInfo = orgInfoMap.get(mbFreshPassenger.getOrgId());
                passengerVo.setDep(mbOrgInfo.getName());
                // 手机号切割出国家码和手机号
                MobilePhoneVo mobilePhoneVo = packageMobilePhoneVo(userInfo.getAreaCode().concat(" ").concat(userInfo.getMobilePhone()));
                passengerVo.setTel(mobilePhoneVo);
                passengerVo.setCorp(true);
                Date birthday = userInfo.getBirthday();
                if (birthday != null) {
                    Instant instant = birthday.toInstant();
                    ZoneId zone = ZoneId.systemDefault();
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
                    DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String format = ftf.format(localDateTime);
                    PassengerVo.Birth birth = new PassengerVo.Birth();
                    birth.setValue(format);
                    passengerVo.setBirth(birth);
                }
                passengerVo.setNationality(userInfo.getNationality());
                String gender = userInfo.getGender();
                passengerVo.setGender(gender);
                passengerVo.setPageEnd(pageEnd);
                passengerVo.setShowPass(true);
                passengerVo.setName(userInfo.getName());
                passengerVo.setMail(userInfo.getEmail());
                passengerVo.setOrgId(mbFreshPassenger.getOrgId());
            } else if (mbFreshPassenger.getNonEmployeeUid() != null) {
                cards = nonUidCardMapList.get(mbFreshPassenger.getNonEmployeeUid());
                MbOrgNonEmployeeInfo userInfo = nonEmployeeInfoMap.get(mbFreshPassenger.getNonEmployeeUid());
                if (userInfo != null) {
                    passengerVo.setNoEmployeeId(userInfo.getId().toString());
                    passengerVo.setName(userInfo.getName());
                    String eName = "";
                    if (StringUtils.isNotBlank(userInfo.getFirstEnName())
                            || StringUtils.isNotBlank(userInfo.getMidEnName()) || StringUtils.isNotBlank(userInfo.getLastEnName())) {
                        eName = (StringUtils.isNotBlank(userInfo.getFirstEnName()) ? userInfo.getFirstEnName() : "")
                                + (StringUtils.isNotBlank(userInfo.getMidEnName()) ? userInfo.getMidEnName() : "")
                                + "/" + (StringUtils.isNotBlank(userInfo.getLastEnName()) ? userInfo.getLastEnName() : "");
                    }
                    passengerVo.setPassport(eName);
                    // 手机号切割出国家码和手机号
                    MobilePhoneVo mobilePhoneVo = packageMobilePhoneVo(userInfo.getMobilePhone());
                    passengerVo.setTel(mobilePhoneVo);
                    passengerVo.setCorp(false);
                    Date birthday = userInfo.getBirthday();
                    if (birthday != null) {
                        LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        String format = dtf.format(localDateTime);
                        PassengerVo.Birth birth = new PassengerVo.Birth();
                        birth.setValue(format);
                        passengerVo.setBirth(birth);
                    }
                    passengerVo.setNationality(userInfo.getNationality());
                    String gender = userInfo.getGender();
                    passengerVo.setGender(gender);
                    passengerVo.setPageEnd(pageEnd);
                    passengerVo.setShowPass(true);
                    passengerVo.setEmp(NO_EMPLOYEE);
                }
            }
            // 封装证件信息
            if (CollectionUtils.isNotEmpty(cards)) {
                List<CardVo> cardVoList = packageCardVo(cards, site);
                passengerVo.setSource(cardVoList);
            }
            CostCenter costCenter = costMap.get(passengerVo.getOrgId());
            if (costCenter == null) {
                if (StringUtils.isNotBlank(passengerVo.getOrgId())) {
                    List<CostCenter> costCenters = costCenterService.getCostCenter(passengerVo.getOrgId());
                    if (CollectionUtils.isNotEmpty(costCenters)){
                        costMap.putIfAbsent(passengerVo.getOrgId(), costCenters.get(0));
                        passengerVo.setCostCenter(costCenter);
                    }
                }
            } else {
                passengerVo.setCostCenter(costCenter);
            }
            returnList.add(passengerVo);
        }
        returnMap.put("plist", returnList);
        return new JSONResult<>(returnMap);
    }

    private MobilePhoneVo packageMobilePhoneVo(String mobilePhone) {
        MobilePhoneVo mobilePhoneVo = new MobilePhoneVo();
        if (StringUtils.isNotBlank(mobilePhone)) {
            String[] s = mobilePhone.split(" ");
            String countryCode = "+86";
            String phone = "";
            if (s.length == 2) {
                countryCode = s[0];
                phone = s[1];
            } else {
                phone = s[0];
            }
            mobilePhoneVo.setCountryCode(countryCode);
            mobilePhoneVo.setValue(phone);
        }
        return mobilePhoneVo;
    }

    private List<CardVo> packageCardVo(List<MbOrgUserIdcard> cards, String site) {
        List<CardVo> cardVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cards)) {
            for (MbOrgUserIdcard card : cards) {
                // 过滤掉学生证
                if (CardCodeEnum.STUDENT_CARD.getCode().equals(card.getCardType().toString())) {
                    continue;
                }
                CardVo cardVo = new CardVo();
                cardVo.setValue(card.getCardNo());
                cardVo.setType(card.getCardType());
                cardVo.setPlaceOfIssue(card.getPlaceOfIssue());
                Date timeLimit = card.getTimeLimit();
                // 证件是否有效
                if (timeLimit != null) {
                    cardVo.setIsValid(timeLimit.after(new Date()));
                } else {
                    cardVo.setIsValid(false);
                }
                cardVo.setValidity(timeLimit);
                cardVo.setName(CardTypeSwitchUtil.getNameById(card.getCardType()));

                cardVoList.add(cardVo);
            }
        }
        // 根据site判断产线，封装默认卡片信息
        // 火车票产线
        if (org.apache.commons.lang3.StringUtils.isNotBlank(site) && site.equals(ProductTypeEnum.TRAIN.getCode())) {
            for (int i = 0; i < cardVoList.size(); i++) {
                if (cardVoList.get(i).getType().equals(CardCodeEnum.ID_CARD.getCode())) {
                    CardVo remove = cardVoList.remove(i);
                    cardVoList.add(remove);
                }
            }
        }
        // 机票产线 优先放身份证，其次是护照，其他身份信息不管排序
        if (org.apache.commons.lang3.StringUtils.isNotBlank(site) && site.equalsIgnoreCase(ProductTypeEnum.FLIGHT.getCode())) {
            Integer idCard = null;
            Integer passport = null;
            for (int i = 0; i < cardVoList.size(); i++) {
                if (cardVoList.get(i).getType().toString().equals(CardCodeEnum.ID_CARD.getCode())) {
                    idCard = i;
                }
                if (cardVoList.get(i).getType().toString().equals(CardCodeEnum.PASSPROT.getCode())) {
                    passport = i;
                }
            }
            if (idCard != null && passport != null) {
                Collections.swap(cardVoList, idCard, 0);
                Collections.swap(cardVoList, passport, 1);
            }
            if (idCard != null && passport == null) {
                Collections.swap(cardVoList, idCard, 0);
            }
            if (idCard == null && passport != null) {
                Collections.swap(cardVoList, passport, 0);
            }

        }
        return cardVoList;
    }

    private Map<String, Object> getPassengerThroughAgent(GetPassengerRequest request) {

        return null;
    }


	/**
	 * 查询出行人列表信息 localhost:7890/passenger/listPassengerInfo
	 *
	 * @param passengerVos
	 * @param passengerVos
	 * @return
	 */
	@RequestMapping("/listPassengerInfo")
	public JSONResult<List<PassengerVo>> listPassengerInfo(@RequestBody List<PassengerVo> passengerVos) {
		if (CollectionUtils.isEmpty(passengerVos)){
			return JSONResult.ok();
		}
		List<PassengerVo> employeeList = passengerVos.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).collect(Collectors.toList());
		List<PassengerVo> nonEmployeeList = passengerVos.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).collect(Collectors.toList());
        List<PassengerVo> result = listPassengerInfo(employeeList, nonEmployeeList, null);
        // 内部soa接口，无需脱敏处理
        SecurityContext.setSecurityAccessible(true);
        return JSONResult.success(result);
	}

    private List<PassengerVo> listPassengerInfo(List<PassengerVo> employeeList, List<PassengerVo> nonEmployeeList, String site) {
        List<PassengerVo> returnList = new ArrayList<>();
        // 员工
        if (CollectionUtils.isNotEmpty(employeeList)) {
            List<String> uids = employeeList.stream().map(PassengerVo::getUid).collect(Collectors.toList());
            List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByUids(uids);
            Map<String, MbOrgEmployeeInfo> employeeInfoMap = employeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
            List<String> orgIds = employeeList.stream().map(PassengerVo::getOrgId).collect(Collectors.toList());
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
            Map<String, MbOrgInfo> orgInfoMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
                orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
            }
            List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(uids);
            Map<String, List<MbOrgUserIdcard>> uidCardMapList = userIdcards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
			Map<String, CostCenter> costMap = Maps.newHashMap();
            for (PassengerVo passengerVo : employeeList) {
                String uid = passengerVo.getUid();
                MbOrgEmployeeInfo mbOrgEmployeeInfo = employeeInfoMap.get(uid);
                mbOrgEmployeeInfo.setOrgId(passengerVo.getOrgId());
				PassengerVo finalData = packageEmployeeData(mbOrgEmployeeInfo, orgInfoMap, uidCardMapList, site);
				CostCenter costCenter = costMap.get(passengerVo.getOrgId());
				if (costCenter == null) {
                    List<CostCenter> costCenters = costCenterService.getCostCenter(passengerVo.getOrgId());
                    if (CollectionUtils.isNotEmpty(costCenters)){
                        costMap.putIfAbsent(passengerVo.getOrgId(), costCenters.get(0));
                        finalData.setCostCenter(costCenter);
                    }
				} else {
					finalData.setCostCenter(costCenter);
				}
                returnList.add(finalData);
            }
        }
        // 非员工
        if (CollectionUtils.isNotEmpty(nonEmployeeList)) {
            List<Long> nonEmployeeUids = nonEmployeeList.stream().map(p -> Long.parseLong(p.getNoEmployeeId())).collect(Collectors.toList());
            List<MbOrgNonEmployeeInfo> nonEmployeeInfoList = organizationNonEmployeeService.listByIds(nonEmployeeUids);
            List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByNonEmployeeUids(nonEmployeeUids);
            Map<Long, List<MbOrgUserIdcard>> uidCardMapList = new HashMap<>();
            if (CollectionUtils.isNotEmpty(userIdcards)) {
                uidCardMapList = userIdcards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getNonEmployeeId));
            }
            if (CollectionUtils.isNotEmpty(nonEmployeeInfoList)) {
                for (MbOrgNonEmployeeInfo userInfo : nonEmployeeInfoList) {
                    PassengerVo passengerVo = packageNonEmployeeData(userInfo, uidCardMapList, site);
                    returnList.add(passengerVo);
                }
            }
        }
        return returnList;
    }

    private PassengerVo packageEmployeeData(MbOrgEmployeeInfo userInfo, Map<String, MbOrgInfo> orgInfoMap, Map<String, List<MbOrgUserIdcard>> uidCardMapList, String site) {
        PassengerVo passengerVo = new PassengerVo();
        // 是否读取nameInfo的数据,T:读取  F:不读取
        boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
        if(nameInfoReadSwitch && StrUtil.isNotBlank(userInfo.getNameInfo())){
            NameInfoBo nameInfoBo = JsonUtils.parse(userInfo.getNameInfo(),NameInfoBo.class);
            passengerVo.setSurname(nameInfoBo.getSurname());
            passengerVo.setGivenname(nameInfoBo.getGivenname());
            passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
            passengerVo.setFullName(nameInfoBo.getFullName());
            passengerVo.setNationality(nameInfoBo.getNationality());
        }else{
            passengerVo.setSurname(userInfo.getLastEnName());
            passengerVo.setGivenname(userInfo.getFirstEnName());
            passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(userInfo.getLastEnName(),userInfo.getFirstEnName()));
            passengerVo.setFullName(userInfo.getName());
            passengerVo.setNationality(userInfo.getNationality());
        }

        passengerVo.setUid(userInfo.getUid());
        String eName = "";
        if (StringUtils.isNotBlank(userInfo.getFirstEnName())
                || StringUtils.isNotBlank(userInfo.getMidEnName()) || StringUtils.isNotBlank(userInfo.getLastEnName())) {
            eName = (StringUtils.isNotBlank(userInfo.getFirstEnName()) ? userInfo.getFirstEnName() : "")
                    + (StringUtils.isNotBlank(userInfo.getMidEnName()) ? userInfo.getMidEnName() : "")
                    + "/" + (StringUtils.isNotBlank(userInfo.getLastEnName()) ? userInfo.getLastEnName() : "");
        }
        passengerVo.setPassport(eName);
        String userOrgId = userInfo.getOrgId();
        MbOrgInfo mbOrgInfo = orgInfoMap.get(userOrgId);
        if (mbOrgInfo != null) {
            passengerVo.setDep(mbOrgInfo.getName());
            passengerVo.setOrgId(mbOrgInfo.getOrgId());
        }
        // 手机号切割出国家码和手机号
        MobilePhoneVo mobilePhoneVo = packageMobilePhoneVo(userInfo.getAreaCode().concat(" ").concat(userInfo.getMobilePhone()));
        passengerVo.setTel(mobilePhoneVo);
        passengerVo.setCorp(true);
        Date birthday = userInfo.getBirthday();
        if (birthday != null) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = dtf.format(localDateTime);
            PassengerVo.Birth birth = new PassengerVo.Birth();
            birth.setValue(format);
            passengerVo.setBirth(birth);
        }
        String gender = userInfo.getGender();
        passengerVo.setGender(gender);
        passengerVo.setShowPass(true);
        passengerVo.setName(userInfo.getName());
        passengerVo.setMail(userInfo.getEmail());
        List<MbOrgUserIdcard> userIdcards = uidCardMapList.get(userInfo.getUid());
        List<CardVo> cardVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userIdcards)) {
            cardVoList = packageCardVo(userIdcards, site);
        }
        passengerVo.setSource(cardVoList);
        return passengerVo;
    }

    private PassengerVo packageNonEmployeeData(MbOrgNonEmployeeInfo userInfo, Map<Long, List<MbOrgUserIdcard>> uidCardMapList, String site) {
        PassengerVo passengerVo = new PassengerVo();
        passengerVo.setNoEmployeeId(userInfo.getId().toString());
        passengerVo.setEmployeeType(2);
        passengerVo.setEmployeeDesc("外部员工");
        passengerVo.setName(userInfo.getName());
        String eName = "";
        if (StringUtils.isNotBlank(userInfo.getFirstEnName())
                || StringUtils.isNotBlank(userInfo.getMidEnName()) || StringUtils.isNotBlank(userInfo.getLastEnName())) {
            eName = (StringUtils.isNotBlank(userInfo.getFirstEnName()) ? userInfo.getFirstEnName() : "")
                    + (StringUtils.isNotBlank(userInfo.getMidEnName()) ? userInfo.getMidEnName() : "")
                    + "/" + (StringUtils.isNotBlank(userInfo.getLastEnName()) ? userInfo.getLastEnName() : "");
        }
        passengerVo.setPassport(eName);
        // 手机号切割出国家码和手机号
        MobilePhoneVo mobilePhoneVo = packageMobilePhoneVo(userInfo.getMobilePhone());
        passengerVo.setTel(mobilePhoneVo);
        passengerVo.setCorp(false);
        Date birthday = userInfo.getBirthday();
        if (birthday != null) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = dtf.format(localDateTime);
            PassengerVo.Birth birth = new PassengerVo.Birth();
            birth.setValue(format);
            passengerVo.setBirth(birth);
        }
        passengerVo.setNationality(userInfo.getNationality());
        String gender = userInfo.getGender();
        passengerVo.setGender(gender);
        passengerVo.setShowPass(true);
        List<MbOrgUserIdcard> userIdcards = uidCardMapList.get(userInfo.getId());
        List<CardVo> cardVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userIdcards)) {
            cardVoList = packageCardVo(userIdcards, site);
        }
        passengerVo.setSource(cardVoList);
        passengerVo.setEmp(NO_EMPLOYEE);
        return passengerVo;
    }

    private List<PassengerVo> getPassengerByTravel(GetPassengerRequest request) {
        List<PassengerVo> returnList = new ArrayList<>();
        // 调用出差申请的soa接口查询人
        String travelId = request.getTravelId();
        Long tripId = request.getTripId();
        String dcity = request.getDcity();
        String acity = request.getAcity();
        //入住时间
        String startDate = request.getStartDate();
        //离店时间
        String endDate = request.getEndDate();
        Integer returnType = request.getReturnType();
        ApplyTripPersonEffectRequest req = new ApplyTripPersonEffectRequest();
        req.setApplyNo(travelId);
        req.setTrafficId(tripId);
        req.setStartCityCode(dcity);
        req.setEndCityCode(acity);
        req.setReturnType(returnType);
        req.setUid(request.getUid());
        req.setOrgId(request.getOrgId());
        req.setStartDate(startDate);
        req.setEndDate(endDate);
        req.setReturnType(request.getReturnType());
        req.setTrafficType(request.getSite());
        List<TripPersonEffectResponse> list = applyTripClientLoader.listEffectTripPerson(req);
        if (CollectionUtils.isEmpty(list)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.APPLY_DONT_PASSENGER);
        }

        List<TripPersonEffectResponse> employeeList = list.stream().filter(p -> p.getEmpStatus() == 1).collect(Collectors.toList());
        List<PassengerVo> employees = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(employeeList)) {
            for (TripPersonEffectResponse temp : employeeList) {
                PassengerVo passengerVo = new PassengerVo();
                passengerVo.setUid(temp.getUid());
                passengerVo.setOrgId(temp.getOrgId());
                employees.add(passengerVo);
            }
        }
        List<TripPersonEffectResponse> nonEmployeeList = list.stream().filter(p -> p.getEmpStatus() == 0).collect(Collectors.toList());
        List<PassengerVo> nonEmployees = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(nonEmployeeList)) {
            for (TripPersonEffectResponse temp : nonEmployeeList) {
                PassengerVo passengerVo = new PassengerVo();
                passengerVo.setNoEmployeeId(temp.getUid());
                passengerVo.setOrgId(temp.getOrgId());
                nonEmployees.add(passengerVo);
            }
        }
        List<PassengerVo> userInfoList = listPassengerInfo(employees, nonEmployees, request.getSite());

        // 将选中的员工排掉
        if (CollectionUtils.isNotEmpty(userInfoList)) {
            if (CollectionUtils.isNotEmpty(request.getSelectedList())) {
				List<PassengerInfo> selectedList = request.getSelectedList();
				List<String> uidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerInfo::getUid).collect(Collectors.toList());
				List<String> noUidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).map(PassengerInfo::getNoEmployeeId).collect(Collectors.toList());
				for (PassengerVo passengerVo : userInfoList) {
					if (passengerVo.getCorp()) {
						if (!uidList.contains(passengerVo.getUid())) {
							returnList.add(passengerVo);
						}
					} else {
						if (!noUidList.contains(passengerVo.getNoEmployeeId())) {
							returnList.add(passengerVo);
						}
					}
                }
            } else {
                returnList = userInfoList;
            }
        }
        return returnList;
    }

    private PassengerVo packageData(MbOrgEmployeeInfo mbOrgEmployeeInfo, String uid) {
        // 没有岗位返回自己，找产品确认，0624确认
        PassengerVo passengerVo = new PassengerVo();
        passengerVo.setUid(mbOrgEmployeeInfo.getUid());
        passengerVo.setName(mbOrgEmployeeInfo.getName());
        String eName = "";
        if (StringUtils.isNotBlank(mbOrgEmployeeInfo.getFirstEnName())
                || StringUtils.isNotBlank(mbOrgEmployeeInfo.getMidEnName()) || StringUtils.isNotBlank(mbOrgEmployeeInfo.getLastEnName())) {
            eName = (StringUtils.isNotBlank(mbOrgEmployeeInfo.getFirstEnName()) ? mbOrgEmployeeInfo.getFirstEnName() : "")
                    + (StringUtils.isNotBlank(mbOrgEmployeeInfo.getMidEnName()) ? mbOrgEmployeeInfo.getMidEnName() : "")
                    + "/" + (StringUtils.isNotBlank(mbOrgEmployeeInfo.getLastEnName()) ? mbOrgEmployeeInfo.getLastEnName() : "");
        }
        passengerVo.setPassport(eName);
        String orgId = mbOrgEmployeeInfo.getOrgId();
        // 通过orgid查询部门信息
        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (mbOrgInfo != null) {
            passengerVo.setDep(mbOrgInfo.getName());
        }
        // 手机号切割出国家码和手机号
        String mobilePhone = mbOrgEmployeeInfo.getMobilePhone();
        MobilePhoneVo mobilePhoneVo = packageMobilePhoneVo(mbOrgEmployeeInfo.getAreaCode().concat(" ").concat(mobilePhone));
        passengerVo.setTel(mobilePhoneVo);
        // 查询用户的证件信息
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(uid);
        if (CollectionUtils.isNotEmpty(cardList)) {
            List<CardVo> list = new ArrayList<>();
            for (MbOrgUserIdcard mbOrgUserIdcard : cardList) {
                CardVo cardVo = new CardVo();
                String cardNo = mbOrgUserIdcard.getCardNo();
                Integer cardType = mbOrgUserIdcard.getCardType();
                Date timeLimit = mbOrgUserIdcard.getTimeLimit();
                cardVo.setName(CardTypeSwitchUtil.getNameById(cardType));
                cardVo.setValue(cardNo);
                cardVo.setValidity(timeLimit);
                cardVo.setType(cardType);
                list.add(cardVo);
            }
            passengerVo.setSource(list);
        }
        // 默认员工
        passengerVo.setCorp(true);
        Date birthday = mbOrgEmployeeInfo.getBirthday();
        if (birthday != null) {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = dtf.format(localDateTime);
            PassengerVo.Birth birth = new PassengerVo.Birth();
            birth.setValue(format);
            passengerVo.setBirth(birth);
        }
        passengerVo.setNationality(mbOrgEmployeeInfo.getNationality());
        String gender = mbOrgEmployeeInfo.getGender();
        passengerVo.setGender(gender);
        passengerVo.setPageEnd(true);
        passengerVo.setShowPass(true);
//            passengerVo.setAge(22);
        passengerVo.setMail(mbOrgEmployeeInfo.getEmail());
        passengerVo.setUid(mbOrgEmployeeInfo.getUid());
        return passengerVo;
    }

    /**
	 * 停用账号同步禁用出行人有效性
	 *
	 * @param updateAccountValidRequest
	 * @return
	 */
	@RequestMapping("/updateAccountValid")
	public JSONResult<Boolean> updateAccountValid(@RequestBody @Valid UpdateAccountValidRequest updateAccountValidRequest) {
		Integer accountValid = updateAccountValidRequest.getAccountValid();
		String uid = updateAccountValidRequest.getUid();
		boolean flag = freshPassengerService.updateAccountValid(uid, accountValid);
		return new JSONResult<>(flag);
	}

	@RequestMapping("/getFreshPassengerRelation")
	public JSONResult<Map<String, PassengerVo>> getFreshPassengerRelation(@RequestBody @Valid GetFreshPassengerRelation getFreshPassengerRelation) {
		Map<String, PassengerVo> map = new HashMap<>();
		Map<String, MbFreshPassengerRelation> exitedMap = null;
		//查询uid 下的常旅
		List<MbFreshPassengerRelation> exitedList = freshPassengerRelationService.selectByUid(getFreshPassengerRelation.getUid());
		if (!CollectionUtils.isEmpty(exitedList)) {
			exitedMap = exitedList.stream().collect(Collectors.toMap(x -> x.getFreshUid(), x -> x, (k1, k2) -> k1));
		}
		MbFreshPassengerRelation mbFreshPassengerRelation = null;
		PassengerVo passengerVo = null;
		for (String uid : getFreshPassengerRelation.getFreshUids()) {
			passengerVo = new PassengerVo();
            if (exitedMap == null || exitedMap.get(uid) == null) {
                passengerVo.setRelationFlag(false);
                map.put(uid, passengerVo);
                continue;
            }
            mbFreshPassengerRelation = exitedMap.get(uid);
            passengerVo.setRelationFlag(true);
            passengerVo.setRelationId(mbFreshPassengerRelation.getId());
            map.put(uid, passengerVo);
        }
        return JSONResult.success(map);
    }

    /**
     * 校验乘客姓名是否重复（包含多音字）
     * http://10.5.119.87:9526/project/27/interface/api/23685
     *
     * @param checkPassengerRequest
     * @return
     */
    @PostMapping("/checkPassengerRepeat")
    public JSONResult checkPassengerRepeat(@RequestBody CheckPassengerRepeatRequest checkPassengerRequest) {
        if (CollectionUtils.isEmpty(checkPassengerRequest.getPassengerList())) {
            return JSONResult.errorMsg("乘客为空");
        }
        CheckPassengerRepeatResponse checkPassengerRepeatResponse = new CheckPassengerRepeatResponse();
        List<PassengerVo> passengerList = checkPassengerRequest.getPassengerList();
        List<String> passengerNameList = passengerList.stream().map(x -> {
                    if ("en".equals(x.getLang()) && !StringUtils.isBlank(x.getPassport())) {
                        return x.getPassport();
                    }
                    return x.getName();
                }
        ).collect(Collectors.toList());
        try {
            CheckRepeatDto checkRepeatDto = Pinyin4jUtil.checkRepeatNew(passengerNameList);
            Boolean check = checkRepeatDto.getCheck();
            if (check) {
                checkPassengerRepeatResponse.setSuccess(Boolean.FALSE);
				Integer count = checkRepeatDto.getCount();
				String msg = count + "位乘客姓名或拼音相同，请分开预订";
				return JSONResult.errorMsg(msg);
			}
		} catch (Exception e) {
			log.error("校验乘客姓名失败：request:" + JsonUtils.toJsonString(checkPassengerRequest), e);
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHECK_ERROR);
		}
		return JSONResult.success(Boolean.TRUE);
	}

	/**
	 * 获取可用的出行人
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/getValidPassengerSoa")
	public JSONResult<GetPassengerResponseBO> getValidPassengerSoa(@RequestBody GetPassengerRequest request) {
		return JSONResult.success(passengerService.getValidPassengerSoa(request));
	}

	/**
	 * 获取可用的出行人
	 *
	 * @param request
	 * @param userInfo
	 * @return
	 */
	@RequestMapping("/getValidPassenger")
	public JSONResult<GetPassengerResponseVO> getValidPassenger(@RequestBody GetPassengerRequestVO request, BaseUserInfo userInfo) {

        if (Objects.isNull(request.getUserInfo())){
            request.setBaseUserInfo(userInfo);
        }
        request.setLoginOrgId(request.getUserInfo().getOrgId());

		String corpPayType = request.getCorpPayType();
		String travelId = request.getTravelId();
		String type;
		if (Objects.equals(corpPayType, CorpPayTypeEnum.PUB.name())) {
            if (StringUtils.isNotBlank(travelId)) {
                ApplyTripRequest applyTripRequest = new ApplyTripRequest();
                applyTripRequest.setApplyNo(travelId);
                applyTripRequest.setCorpId(userInfo.getCorpId());
                AoApplyTripTempVo applyTemp = applyTripClientLoader.getApplyTemp(applyTripRequest);
                //不校验出行人的话，按pub处理
                if (applyTemp.getTripPerson() != 2) {
                    type = "PUB";
                } else {
                    type = "TRAVEL";
                }
			} else {
				type = "PUB";
			}
		} else {
			type = "OWN";
		}
        GetPassengerResponseVO passengerResponseVO = passengerServiceFactory.getByType(type).getPassenger(request);
		passengerResponseVO.setNameEditDuringBooking(passengerService.getNameEditDuringBooking(Optional.ofNullable(request.getOrgId()).orElse(request.getUserInfo().getOrgId())));
        return JSONResult.success(passengerResponseVO);
	}

	@RequestMapping("/getPassengerByUid")
	public JSONResult<List<GetPassengerByUidResponse>> getPassengerByUid (@RequestBody getPassengerByUidRequest request) {
        List<GetPassengerByUidResponse> responses = passengerService.getPassengerByUid(request);
	    return JSONResult.success(responses);
    }

    @RequestMapping("/getPassengerName")
    public JSONResult<List<GetPassengerNameResponse>> getPassengerName(@RequestBody List<GetPassengerNameRequest> request){
        return JSONResult.success(passengerService.getPassengerName(request));
    }
    @RequestMapping("/savePassenger")
    public JSONResult<SavePassengerResponse> savePassenger(@RequestBody SavePassengerRequest request, BaseUserInfo userInfo){
	    log.info("开始保存出行人信息");
	    request.setUid(userInfo.getUid());
	    return JSONResult.success(passengerService.savePassenger(request));
    }

    @RequestMapping("/monitorPassengerName")
    public JSONResult<Boolean> monitorPassengerName(@RequestBody MonitorPassengerNameRequest request){
	    return JSONResult.success(passengerService.monitorPassengerName(request));
    }

    @RequestMapping("/addOrUpdatePassenger")
    public JSONResult<AddOrUpdatePassengerResponse> addOrUpdatePassenger(@RequestBody AddOrUpdatePassengerRequest request, BaseUserInfo baseUserInfo){
	    return JSONResult.success(passengerService.addOrUpdatePassenger(request, baseUserInfo));
    }

    @RequestMapping("/updateFreshEnNameBatch")
    public JSONResult<Boolean> updateFreshEnNameBatch(){
	    return JSONResult.success(passengerService.updateFreshEnNameBatch());
    }

    @RequestMapping("/checkPassengerNew")
    public JSONResult<CheckPassengerResponse> checkPassengerNew(@RequestBody CheckPassengerRequest request, BaseUserInfo baseUserInfo){
        CheckPassengerRequest checkPassengerRequest = passengerService.checkPassengerNew(request, baseUserInfo);
        checkPassenger(checkPassengerRequest);
        return JSONResult.success(passengerService.checkPassengerResponseConvert(checkPassengerRequest));
    }

    /**
     * 删除外部出行人信息，仅创建人有权删除
     * @param request
     * @param userInfo
     * @return
     */
    @RequestMapping("/deleteNonEmployeePassenger")
    public JSONResult<Boolean> deleteNonEmployeePassenger(@RequestBody DeletePassengerRequest request, BaseUserInfo userInfo){
        log.info("删除外部人员信息-只能是创建人可删");
        request.setUid(userInfo.getUid());
        return JSONResult.success(passengerService.deleteNonEmployeePassenger(request));
    }

    /**
     * 查询机构用户是否开启企业订购业务
     * @param request
     * @return
     */
    @RequestMapping("/getOrderResultByPassengersSoa")
    public JSONResult<List<OrderResultPassengerResponse>> getOrderResultByPassengersSoa(@RequestBody OrderResultPassengerRequest request){
        return JSONResult.success(passengerService.getOrderResultByPassengers(request));
    }

}

